<template>
  <div class="task-manage-container">
    <!-- 队伍选择器 -->
    <div class="team-selector" v-if="teams.length > 0">
      <van-picker
        show-toolbar
        title="选择队伍"
        :columns="teamOptions"
        :default-index="currentTeamIndex"
        @confirm="handleTeamChange"
        @cancel="handleTeamCancel"
      />
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <div class="filter-tabs">
        <div
          :class="['tab', activeTab === 'all' ? 'active' : '']"
          @click="switchTab('all')"
        >
          全部任务
        </div>
        <div
          :class="['tab', activeTab === 'my' ? 'active' : '']"
          @click="switchTab('my')"
        >
          我的任务
        </div>
        <div
          :class="['tab', activeTab === 'created' ? 'active' : '']"
          @click="switchTab('created')"
        >
          我创建的
        </div>
      </div>

      <div class="filter-options">
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="statusFilter"
            :options="statusOptions"
            title="状态"
          />
        </van-dropdown-menu>
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="priorityFilter"
            :options="priorityOptions"
            title="优先级"
          />
        </van-dropdown-menu>
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="sortFilter"
            :options="sortOptions"
            title="排序"
          />
        </van-dropdown-menu>
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索任务标题或描述"
        show-action
        @search="handleSearch"
        @clear="handleClearSearch"
      >
        <template #action>
          <div @click="handleSearch">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 任务列表 -->
    <div class="task-list">
      <van-loading v-if="loading" color="#1989fa" />
      <div v-else-if="tasks.length === 0" class="empty-tip">
        <van-empty description="暂无任务" />
      </div>
      <div v-else class="task-items">
        <div
          v-for="task in tasks"
          :key="task.id"
          class="task-item"
          @click="navigateToTaskDetail(task.id)"
        >
          <div class="task-header">
            <h3 class="task-title">{{ task.task_title }}</h3>
            <div :class="['priority-badge', `priority-${task.priority}`]">
              {{ getPriorityText(task.priority) }}
            </div>
          </div>
          <div class="task-info">
            <div class="team-name">所属队伍：{{ task.team?.name || '未知队伍' }}</div>
            <div class="assignee">
              负责人：
              <span v-if="task.assigneeList && task.assigneeList.length > 0">
                <span v-for="(assignee, index) in task.assigneeList" :key="assignee.id">
                  {{ assignee.username }}{{ index < task.assigneeList!.length - 1 ? '、' : '' }}
                </span>
              </span>
              <span v-else>未分配</span>
            </div>
          </div>
          <div class="task-progress">
            <van-progress :percentage="task.progress" :color="getProgressColor(task.progress)" />
            <span class="progress-text">{{ task.progress }}%</span>
          </div>
          <div class="task-footer">
            <div :class="['status-badge', `status-${task.status}`]">
              {{ getStatusText(task.status) }}
            </div>
            <div class="deadline" :class="{ 'deadline-warning': isDeadlineWarning(task) }">
              {{ task.deadline ? formatDate(task.deadline) : '无截止日期' }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > pageSize">
      <van-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total-items="total"
        :show-page-size="false"
        @change="handlePageChange"
      />
    </div>

    <!-- 悬浮新增任务按钮 -->
    <div class="floating-add-btn" @click="navigateToAddTask">
      <van-icon name="plus" size="24" color="#fff" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { taskStore } from '../stores/task/task';
import { userStore } from '../stores/user/user';
import { teamStore } from '../stores/team/team';
import type { Task } from '../models/task';

const router = useRouter();
const route = useRoute();
const taskStoreAPI = taskStore();
const userStoreAPI = userStore();
const teamStoreAPI = teamStore();

// 状态管理
const loading = ref(false);
const tasks = ref<Task[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const activeTab = ref<'all' | 'my' | 'created'>('all');
const statusFilter = ref('');
const priorityFilter = ref('');
const sortFilter = ref('0');
const searchKeyword = ref('');

// 队伍相关
const teams = ref<any[]>([]);
const currentTeamId = ref(0);

// 筛选选项
const statusOptions = [
  { text: '全部', value: '' },
  { text: '未开始', value: '0' },
  { text: '进行中', value: '1' },
  { text: '已完成', value: '2' },
  { text: '已延期', value: '3' },
];

const priorityOptions = [
  { text: '全部', value: '' },
  { text: '低', value: '1' },
  { text: '中', value: '2' },
  { text: '高', value: '3' },
];

const sortOptions = [
  { text: '默认排序', value: '0' },
  { text: '优先级倒序', value: '1' },
  { text: '截止日期正序', value: '2' },
  { text: '截止日期倒序', value: '3' },
];

// 计算属性
const teamOptions = computed(() => {
  return teams.value.map(team => ({ text: team.name, value: team.id }));
});

const currentTeamIndex = computed(() => {
  return teams.value.findIndex(team => team.id === currentTeamId.value);
});

// 获取优先级文本
const getPriorityText = (priority: number) => {
  const map = { 1: '低', 2: '中', 3: '高' };
  return map[priority as keyof typeof map] || '未知';
};

// 获取状态文本
const getStatusText = (status: number) => {
  const map = { 0: '未开始', 1: '进行中', 2: '已完成', 3: '已延期' };
  return map[status as keyof typeof map] || '未知';
};

// 获取进度条颜色
const getProgressColor = (progress: number) => {
  if (progress === 100) return '#52c41a';
  if (progress > 70) return '#1989fa';
  if (progress > 30) return '#faad14';
  return '#f5222d';
};

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 判断是否需要截止日期警告
const isDeadlineWarning = (task: Task) => {
  if (!task.deadline || task.status === 2) return false;
  const deadline = new Date(task.deadline);
  const now = new Date();
  const diffDays = Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
  return diffDays <= 1 && diffDays >= 0;
};

// 处理队伍切换
const handleTeamChange = (value: string) => {
  currentTeamId.value = Number(value);
  taskStoreAPI.setCurrentTeamId(currentTeamId.value);
  refreshTaskList();
};

const handleTeamCancel = () => {
  // 取消不做任何操作
};

// 切换标签页
const switchTab = (tab: 'all' | 'my' | 'created') => {
  activeTab.value = tab;
  refreshTaskList();
};

// 搜索处理
const handleSearch = () => {
  refreshTaskList();
};

const handleClearSearch = () => {
  searchKeyword.value = '';
  refreshTaskList();
};

// 分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  refreshTaskList();
};

// 刷新任务列表
const refreshTaskList = async () => {
  loading.value = true;
  try {
    let res;
    const params = {
      teamId: currentTeamId.value || undefined,
      status: statusFilter.value ? Number(statusFilter.value) : undefined,
      priority: priorityFilter.value ? Number(priorityFilter.value) : undefined,
      keyword: searchKeyword.value || undefined,
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    // 根据标签页选择不同的API
    if (activeTab.value === 'my') {
      res = await taskStoreAPI.fetchMyTasks(params);
    } else if (activeTab.value === 'created') {
      const currentUser = await userStoreAPI.getCurrentUser();
      res = await taskStoreAPI.fetchTaskList({
        ...params,
        creatorId: currentUser?.id,
      });
    } else {
      res = await taskStoreAPI.fetchTaskList(params);
    }

    if (res.code === 200) {
      tasks.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  } catch (error) {
    showToast('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

// 导航到任务详情
const navigateToTaskDetail = (taskId: number) => {
  router.push(`/task/detail/${taskId}`);
};

// 导航到添加任务
const navigateToAddTask = () => {
  currentTeamId.value = 1;
  if (currentTeamId.value) {
    router.push(`/task/add?teamId=${currentTeamId.value}`);
  } else if (teams.value.length > 0) {
    router.push(`/task/add?teamId=${teams.value[0].id}`);
  } else {
    showToast('请先创建或加入队伍');
    router.push('/team');
  }
};

// 初始化数据
onMounted(async () => {
  // 获取用户信息
  const currentUser = await userStoreAPI.getCurrentUser();
  if (!currentUser) {
    showToast('请先登录');
    router.push('/login');
    return;
  }

  // 获取用户加入的队伍
  try {
    const teamsRes = await teamStoreAPI.getJoinTeams();
    if (teamsRes.code === 200) {
      teams.value = teamsRes.data || [];
      if (teams.value.length > 0) {
        currentTeamId.value = teams.value[0].id;
        taskStoreAPI.setCurrentTeamId(currentTeamId.value);
      }
    }
  } catch (error) {
    console.error('获取队伍列表失败:', error);
  }

  // 初始化任务列表
  refreshTaskList();
});
</script>

<style scoped>
.task-manage-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
  position: relative;
}

.team-selector {
  background-color: #fff;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.filter-bar {
  background-color: #fff;
  padding: 8px 0;
  margin-bottom: 10px;
}

.filter-tabs {
  display: flex;
  padding: 0 16px;
  margin-bottom: 10px;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 8px;
  border-bottom: 2px solid transparent;
  font-size: 14px;
}

.tab.active {
  color: #1989fa;
  border-bottom-color: #1989fa;
  font-weight: 600;
}

.filter-options {
  display: flex;
  padding: 0 16px;
  gap: 10px;
}

.search-bar {
  padding: 0 16px 10px;
}

.task-list {
  padding: 0 16px;
}

.task-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.task-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 10px;
}

.priority-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.priority-1 {
  background-color: #f0f9ff;
  color: #1989fa;
}

.priority-2 {
  background-color: #fff7e6;
  color: #faad14;
}

.priority-3 {
  background-color: #fff1f0;
  color: #f5222d;
}

.task-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.team-name,
.assignee {
  margin-bottom: 4px;
}

.task-progress {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

:deep(.van-progress) {
  flex: 1;
}

.progress-text {
  margin-left: 10px;
  font-size: 12px;
  color: #666;
  min-width: 30px;
  text-align: right;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-0 {
  background-color: #f5f5f5;
  color: #999;
}

.status-1 {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-2 {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-3 {
  background-color: #fff1f0;
  color: #f5222d;
}

.deadline {
  font-size: 12px;
  color: #666;
}

.deadline-warning {
  color: #f5222d;
  font-weight: 600;
}

.pagination {
  padding: 20px 16px 10px;
  background-color: #fff;
  margin-top: 10px;
}

.empty-tip {
  padding: 40px 0;
}

/* 悬浮按钮样式 */
.floating-add-btn {
  position: fixed;
  bottom: 10vh;
  right: 2vh;
  width: 7vh;
  height: 7vh;
  border-radius: 50%;
  background-color: #1989fa;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.4);
  z-index: 100;
  cursor: pointer;
  transition: all 0.3s ease;
}

.floating-add-btn:active {
  transform: scale(0.95);
  background-color: #096dd9;
}
</style>